package allele_convertion;
use 5.8.4;
our @EXPORT_OK=qw(convert_alleles flip_allele get_chromosome_number get_snp_value);
use Exporter;
our @ISA = qw(Exporter);

# Apply the flip Rule: A<->T, C<->G 
# Input: allele
# Output: flipped allele
sub flip_allele
{

   if ($_[0] eq "A")
   {
      return "T";
   }
   elsif ($_[0] eq "T")
   {
      return "A";
   }
   elsif ($_[0] eq "C")
   {
      return "G";
   }
   elsif ($_[0] eq "G")
   {
      return "C";
   }
   
   return "";
};

# Apply the allele convertion rules
# Input: iStrand, sStrand, alleleA, alleleB
# Output: alleleA', alleleB', reverse ("true" or "false")
sub convert_alleles
{
   if ($_[0] eq "BOT" && $_[1] eq "BOT")
   {
      return ($_[2], $_[3], "true");
   }
   
   if ($_[0] eq "BOT" && $_[1] eq "TOP")
   {
      return (flip_allele($_[2]), flip_allele($_[3]), "false");
   }

   if ($_[0] eq "TOP" && $_[1] eq "BOT")
   {
      return (flip_allele($_[2]), flip_allele($_[3]), "true");
   }

   if ($_[0] eq "TOP" && $_[1] eq "TOP")
   {
      return ($_[2], $_[3], "false");
   }
   
   return ();
};

# Returns the chromosome number
# Input: chromosome string
# Output: 1-22, 23 is X, 24 is Y, 25 is XY, 26 is Mt, -9 is unknown
sub get_chromosome_number
{
   my $chromosome = $_[0];
   if ($chromosome eq "X" || $chromosome eq "x")
   {
      $chromosome = "23";
   }
   elsif ($chromosome eq "Y" || $chromosome eq "y")
   {
      $chromosome = "24";
   }
   elsif ($chromosome eq "XY" || $chromosome eq "xy")
   {
      $chromosome = "25";
   }
   elsif ($chromosome eq "MT" || $chromosome eq "Mt" || $chromosome eq "mt")
   {
      $chromosome = "26";
   }
   elsif ($chromosome eq "---")
   {
      $chromosome = "-9";
   }
   
   return $chromosome;
};


# Returns the snp value (0, 1, 2, or -9) based on the alleles
# Input: snpA, snpB, alleleA, alleleB
# Output: snp value (-1 means non-matching snps and alleles)
sub get_snp_value
{
   my $snpval;
   if ($_[0] eq "-") # snpA == '-'
   {
      $snpval = -9;
   }
   elsif ($_[0] ne $_[1]) # snpA != snpB
   {
      $snpval = 1;
   }
   elsif ($_[0] eq $_[2]) # snpA == alleleA (snpA == snpB implied)
   {
      $snpval = 0;
   }
   elsif ($_[0] eq $_[3]) # snpA == alleleB (snpA == snpB implied)
   {
      $snpval = 2;
   }
   else # Something went wrong
   {
      $snpval = -1;
   }
   
   return $snpval;
}

